package com.example.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.ProjectInfoMapper;
import com.example.dao.UxJbcardMapper;
import com.example.dao.UxenglstMapper;
import com.example.dao.UxpmStckMapper;
import com.example.dao.UxtpMapper;
import com.example.dao.UxmadsMapper;
import com.example.entity.Drawing;
import com.example.entity.JOBCard;
import com.example.entity.JobcardWeIdListMA;
import com.example.entity.ProjectShell;
import com.example.entity.RequiredMaterialDetail;
import com.example.entity.SchedulePlanEngineering;
import com.example.exchange.MapUtils;
import com.example.exchange.ServiceUtil;
import com.example.exchange.XMLHeaderConstants;
import com.example.service.AutoJobcArdServer;
import com.example.util.XMLResUtil;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;

import net.sf.json.JSONObject;

import com.example.exchange.UnifierWebServicesUfbs;

@Service
public class AutoJobcArdMAServerImpl extends Util implements AutoJobcArdServer {

	@Autowired
	private UxenglstMapper uxenglstMapper;
	@Autowired
	private UxpmStckMapper uxpmStckMapper;
	@Autowired
	private UxJbcardMapper uxJbcardMapper;
	@Autowired
	private ProjectInfoMapper projectInfoMapper;

	/**
	 * 自动同步 jobcard 物料缺失
	 * 
	 * @throws IOException
	 */
	public void auto_synchro_UXMMT() throws IOException {

		List<Map<String, String>> list = uxJbcardMapper.select_Jbcard_Material_Part(); // 查询出构件中的零件在即时库存中为0的
		if (list.size() != 0) {
			uxJbcardMapper.delete_uxdram();
			uxJbcardMapper.delete_uxdram_PERM();

			Set<String> DrawingSet = new HashSet<String>();

			List<Map<String, String>> list2 = uxJbcardMapper.select_Jbcard_Material_CUT();// 查询出目前下切缺母材的 需产生的零件编码
			for (Map<String, String> index : list) {
				for (Map<String, String> index2 : list2) {
					if (index.get("PART_NO").equals(index2.get("MATERIAL_CODE"))) {
						DrawingSet.add(index2.get("DRAWING_NO"));// 筛入缺母材，相关MTO
						DrawingSet.add(index2.get("DRAWING_NO"));// 筛入缺母材，相关MTO
						index.put("JOBCard_No_1", index2.get("DRAWING_NO"));
						index.put("Rev_1", index2.get("REV"));
						if (index2.get("MATERIAL_STATUS").equals("NOK")) {
							index.put("Material_Sort", "bulk"); // 缺母材
						} else {
							index.put("Material_Sort", "part");
						}
						break;
					}

				}

			}
			List<Map<String, String>> listMto = uxJbcardMapper.select_Jbcard_Material_MTO(DrawingSet);

			for (Map<String, String> index : list) {
				for (Map<String, String> index2 : listMto) {
					String DRAWING_NO = index.get("JOBCard_No_1");
					String REV = index.get("Rev_1");
					if (index2.get("DRAWING_NO").equals(DRAWING_NO) && index2.get("REV").equals(REV)) {
						index.put("MATERIAL_NAME", index2.get("MATERIAL_NAME"));
						index.put("MTO_NO", index2.get("MTO_NO"));
						index.put("TECHNICAL_REQUIREMENT", index2.get("TECHNICAL_REQUIREMENT"));
						System.err.println(index);
					}
				}
			}
			Integer id = uxJbcardMapper.select_uxdram_MaxID();
			if (id == null) {
				id = 1;
			} else {
				id++;
			}
			for (int i = 0; i < list.size() / 500 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
				List<Map<String, String>> index = new ArrayList<Map<String, String>>();
				if ((i + 1) * 500 > list.size())
					index = list.subList(i * 500, list.size());
				if ((i + 1) * 500 <= list.size())
					index = list.subList(i * 500, (i + 1) * 500);
				if (index.size() != 0) {
					uxJbcardMapper.INSERT_uxdram(list, id);
					uxJbcardMapper.INSERT_uxdram_PERM(list, id);
					id = id + index.size();
				}
			}
		}

	}

	/**
	 * 自动生成MA 设备专业JOBcard
	 * 
	 * @throws IOException
	 */
	public void auto_GenerateJobcard_MA() throws IOException {
		// 1-查询符合条件的图纸（列表）,每次取单个图纸

		JOBCard jobcard = null;
		ProjectShell project = null;
		List<SchedulePlanEngineering> list = uxenglstMapper.selectUxenglstJobcArdMA();// 查询满足条件的图纸
		for (SchedulePlanEngineering index : list) {
			jobcard = new JOBCard();
			project = projectInfoMapper.select_ProjectShellDetail(index.getProject_id()); // 查询项目信息
			// 赋值JB 编号，对应合同号，业主
			jobcard.setContract_No(project.getContractNo()); // 合同号
			jobcard.setClient(project.getClient());// 客户
			// 赋值JB 模块号，专业，工序，工作车间 ,工作包号
			jobcard.setWork_Package_No(index.getWork_Package_No());
			jobcard.setModule_Number(index.getModule_Name());
			jobcard.setDiscipline(index.getDiscipline());
			jobcard.setWork_Location(jobcard.getDiscipline() + " Workshop");
			// 更新图纸及版本信息
			jobcard.setDrawing_No(index.getDrawing_No());
			jobcard.setDrawing_Name(jobcard.getDrawing_No());
			jobcard.setDrawing_Version(index.getRev());
			if (index.getDrawing_Category().equals("shop")) { // 图纸类型是安装类型的话
				String Jobcard_NO = index.getModule_Name() + "-" + index.getLoc() + "-MA-INS";
				jobcard.setJOBCard_No(Jobcard_NO);
				jobcard.setMaterial_Progress("0%");
				jobcard.setMaterial_Status("Preparing");
				List<RequiredMaterialDetail> RequiredMaterials = uxpmStckMapper.selectUxpmstck_Drawing_No_bulk(index.getDrawing_No(),index.getRev(),
						project.getProjectObjectid());
				RequiredMaterials
						.addAll(uxpmStckMapper.selectUxpmstck_Drawing_No_tag(index.getDrawing_No(),index.getRev(), project.getProjectObjectid()));

				RequiredMaterials
						.addAll(uxpmStckMapper.selectUxpmstck_Drawing_No_Part2(index.getDrawing_No(),index.getRev(), project.getProjectObjectid()));

				List<JobcardWeIdListMA> dataList = uxJbcardMapper.selectWeIdListMA(jobcard.getDrawing_No(),
						jobcard.getDrawing_Version(), index.getProject_id());

				insertJobcArdMA(index, RequiredMaterials, null, dataList, jobcard, project);
				// 插入创建jobcArd
				// 将生成JObc ard 的 图纸状态改变为已生成JObcard
				// uxenglstMapper.updateTriggerStatusV2(index.getProject_id(),
				// index.getRecord_no());
			}

		}

	}

	/**
	 * 为设备专业根据优先级别自动备料
	 * 
	 * @throws IOException
	 */
	public void auto_IssuedJobcardMA() throws IOException {

		JOBCard jobcard = new JOBCard();
		List<Map<String, String>> projectInfoMaps = projectInfoMapper.select_ProjectID_Number(); // 查找出所有项目
		for (Map<String, String> projectInfoMap : projectInfoMaps) { // 遍历
			Object object = projectInfoMap.get("PID");
			int projectId = Integer.parseInt(String.valueOf(object));

			List<Integer> MaterPri1s = uxJbcardMapper.selectUXMPP_MaterPri(projectId, "MA"); // 查出第一序列备料优先级

			for (Integer MaterPri1 : MaterPri1s) { // 循环第一序列

				List<Map<String, String>> tags = uxJbcardMapper.selectjobcard_MaterialPreparationMA_tag(projectId,
						MaterPri1);

				for (Map<String, String> tag : tags) {

					if (tag.get("DRAWING_NO") != null && tag.get("JOBC_RECORD_NO") != null) {// 无图纸信息或无预Jobcard

						if (tag.get("CHANGED_STATUS").equals("hold")) { // 如果图纸状态是变更或暂停 则停止备料 或跳过此图的备料
							continue;
						} else if (tag.get("CHANGED_STATUS").equals("changed")) {// 如果图纸状态是变更或暂停 则停止备料 或跳过此图的备料
							break;

						}

						if (tag.get("MATERIAL_STATUS").equals("NOK")) {// 如果未备料

							Object object1 = tag.get("ACTIVE_QTY");
							double ACTIVE_QTY = Double.valueOf(String.valueOf(object1));
							Object object2 = tag.get("TOTAL_QTY");
							double TOTAL_QTY = Double.valueOf(String.valueOf(object2));

							if (TOTAL_QTY <= ACTIVE_QTY) {
								List<Map<String, String>> bulks = uxJbcardMapper
										.selectjobcard_MaterialPreparationMA_bulk(projectId, tag.get("DRAWING_NO"),
												tag.get("REV")); // 查出所有未下发的Jobacrd 是否备料齐全
								boolean is = true;
								for (Map<String, String> data : bulks) {
									Object NO = data.get("NO"); // BigDecimal 要先转为Object
									int projectNO = Integer.parseInt(String.valueOf(NO));
									if (projectNO > 0) { // 如果齐全则往下备料
										is = false;
										break;
									}
								}

								if (is) {
									List<Map<String, String>> parts = uxJbcardMapper
											.selectjobcard_MaterialPreparationMA_Part(projectId, tag.get("DRAWING_NO"),
													tag.get("REV")); // 查出未下发的Jobacrd 是否备料齐全
									for (Map<String, String> data : parts) {
										Object NO = data.get("NO"); // BigDecimal 要先转为Object
										int projectNO = Integer.parseInt(String.valueOf(NO));
										if (projectNO > 0) { // 如果齐全则往下备料
											is = false;
											break;
										}
									}

									if (is) {
										jobcard.setRecord_no(tag.get("JOBC_RECORD_NO"));
										String xml = ServiceUtil.createXML(false, XMLHeaderConstants.BP, JOBCard.class,
												MapUtils.java2Map(jobcard));
										xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
										UnifierWebServicesUfbs UnifierWebServicesUDF = new UnifierWebServicesUfbs();

										String oprionsXml = " <options><WFCurrentStepName>Discipline Engineer Check</WFCurrentStepName>"
												+ "<WFActionName>Material Preparation Completed</WFActionName></options>";
										// WFCurrentStepName 当前步骤名称 WFActionName执行的操作名称

										String mgs = this.processResult(UnifierWebServicesUDF.updateBPRecordV2(
												projectInfoMap.get("PROJECTNUMBER"), "JOBCard List", xml, oprionsXml));
										System.err.println(mgs);
										if (mgs.equals("Success")) { // 工作流推送成功则进行物料锁定
											parts.addAll(bulks);
											parts.add(tag);
											uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(tag.get("JOBC_RECORD_NO")); // 修改jobcard状态
											uxpmStckMapper.updateUxpmStckTotal(parts);// 锁定库存
										} else if (mgs.equals(" Failed, WFCurrentStepName is not correct.")) {
											parts.addAll(bulks);
											parts.add(tag);
											uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(tag.get("JOBC_RECORD_NO")); // 修改jobcard状态
											uxpmStckMapper.updateUxpmStckTotal(parts);// 锁定库存
										} else {
											break; // 结束此序列的备料（第一序列）
										}
									}
								}

							} else {
								break;// 结束此序列的备料（第一序列）
							}
						}

					} else {// 结算此序列备料
						break;// 结束此序列的备料（第一序列）
					}

				}
			}

		}
	}

	// 自动审批图纸
	@SuppressWarnings("unused")
	public void auto_IssuedJobcardPI_Approve2() throws IOException {
		UnifierWebServicesUfbs service = new UnifierWebServicesUfbs();
		Drawing Drawing = new Drawing();
		List<String> datas = uxenglstMapper.selectUxenglst_Pending(1014,"PI");
		for (String data : datas) {
			Drawing.setRecord_no(data); // jobcard 的记录ID 查出所有料满足的 jobcard
			String xml = ServiceUtil.createXML(false, XMLHeaderConstants.BP, Drawing.class, MapUtils.java2Map(Drawing));
			xml = XMLResUtil.ResBPExchange(xml, Drawing.class);
			System.err.println(xml);
			String oprionsXml = " <options><WFCurrentStepName>Check By</WFCurrentStepName>"
					+ "<WFActionName>Agree</WFActionName></options>";
			System.err.println(this.processResult(service.updateBPRecordV2("TBJN0149", "Drawing List", xml, oprionsXml)));

		}

	}


}
